package _1Cookie;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.xml.internal.bind.v2.runtime.Name;

@WebServlet("/Exercise")
public class Exercise extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter pw = resp.getWriter();

		String username = req.getParameter("username");

		if (username == null) {
			pw.print("<h1>用户访问</h1>\r\n" + "<form action=\"Exercise\" method=\"get\">\r\n"
					+ "请输入用户名：<input type=\"text\" name=\"username\"><br/>\r\n"
					+ "<input type=\"submit\" value=\"确定\" />");
		} else {

			Cookie c1 = new Cookie("username", username);
			c1.setMaxAge(3);
			resp.addCookie(c1);

			Cookie[] cookies = req.getCookies();

			if (cookies != null) {
				for (int i = 0; i < cookies.length; i++) {
					Cookie c = cookies[i];
					if(c.getName().equals("username")) {
					pw.print(c.getValue() + ",欢迎你！");
				    
					}
				}
			} else {
				pw.print("<h1>用户访问</h1>\r\n" + "<form action=\"Exercise\" method=\"get\">\r\n"
						+ "请输入用户名：<input type=\"text\" name=\"username\"><br/>\r\n"
						+ "<input type=\"submit\" value=\"确定\" />");
			}
		}

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}